// pages/user/invoice/invoice.js
const config = getApp().globalData.config
const T = getApp().globalData.T
let token = ''

Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    isLoaded: false,
    isFirstTip: true,
    page: 1,
    size: 10,
    imageIcon: ['/resource/image/checkbox_normal.png', '/resource/image/checkbox_selected.png', '/resource/image/checkbox_disable.png'],
    iconIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    token = getApp().globalData.token;
    this.getList();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  getList() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'invoice/list',
      method: 'GET',
      data: {
        token: token,
        page: this.data.page,
        size: this.data.size
      },
      success: (res) => {
        if (res.rowCount == this.data.list.length) {
          this.data.isLoaded = true;
          return
        }
        this.setData({
          list: this.data.list.concat(res.list)
        })
      }
    })

  },

  onToinvoice() {
    wx.navigateTo({
      url: './to-invoice/to-invoice',
    })
  },

  onJumpDetail(e) {
    let id = e.currentTarget.dataset.id;
    let status = e.currentTarget.dataset.status;
    let index = e.currentTarget.dataset.index;
    if (status == 1) {
      wx.navigateTo({
        url: './record/record?id=' + id,
      })
    } else if (status == 0) {
      let k = this.data.list[index].selected;
        this.setData({
          [`list[${index}].selected`] : !k
        })
    }
  },

  onReachBottom: function() {
    if (this.data.isLoaded) {
      if (this.data.isFirstTip) {
        T.toast({
          id: '#toast',
          text: '已加载完全部数据了'
        });
      }
      this.data.isFirstTip = false;
      return;
    }
    this.data.page += 1;
    this.getList();
  },

  onBilling() {
    let _temArr = [];
    this.data.list.forEach(m => {
      if (m.selected && m.invoiceStatus == 0) {
        _temArr.push({
          invoiceId: m.invoiceId,
          infoId: m.infoId
        })
      }
    });
    if (this.data.list.length == 0) return ;
    if (_temArr.length == 0) {
      T.toast({id: '#toast', text: '请选择开票'});
      return ;
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'invoice/more?token=' + token,
      method: 'PUT',
      data: _temArr,
      success: (res) => {
        T.toast({ id: '#toast', text: '开票成功', success: () => {
          this.data.list.map(m => {
            if (m.selected) {
              m.invoiceStatus = 1;
            }
          })
        } });
      }
    })

  }

})